package com.jp.knowledge.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jp.knowledge.util.L;

import java.util.List;

/**
 * Created by jiayen on 16/11/4.
 * recycleViewHolder
 */

public abstract class JpBaseRecyViewAdapter extends RecyclerView.Adapter<JPRecycleViewHolder> implements View.OnClickListener {

    protected OnItemListerner onItemListener;
    protected List data;
    protected Context mContext;

    public JpBaseRecyViewAdapter(Context context,List data) {
        this.data = data;
        this.mContext = context;
    }

    public void updataAdapter(List list){
        this.data=list;
        notifyDataSetChanged();
    }

    public List getData() {
        return data;
    }

    protected Object getItem(int postion){
        return  data == null?null:data.get(postion);
    }

    @Override
    public JPRecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(getLayoutId(), parent, false);
        JPRecycleViewHolder viewholder = new JPRecycleViewHolder(view);
        onItemClickEvent(viewholder);
        L.e("onCreateViewHolder===viewType==" + viewType);
        return viewholder;
    }

    public  abstract   int getLayoutId();

    /**
     * item点击事件
     * @param onItemListener
     */
    public void setOnItemListener(OnItemListerner onItemListener) {
        this.onItemListener = onItemListener;
    }

    /**
     * item点击事件
     *
     * @param viewholder
     */
    private void onItemClickEvent(JPRecycleViewHolder viewholder) {
        if (onItemListener != null) {
            viewholder.itemView.setOnClickListener(this);
        }
    }

    @Override
    public void onBindViewHolder(JPRecycleViewHolder holder, int position) {
        holder.itemView.setTag(position);
        bindViewHold(holder,position);
    }

    public abstract   void  bindViewHold(JPRecycleViewHolder holder, int position);
    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public void onClick(View view) {
        if (onItemListener != null) {
            int position = (int) view.getTag();
            onItemListener.onItemClick(view, position);
        }
    }

    public  void removeItem(int position){
        data.remove(position);
        notifyItemRemoved(position);
    }
}
